package com.ninth_group.dao.Impl;

import com.ninth_group.dao.CityDao;
import com.ninth_group.function.TriFunction;
import com.ninth_group.po.City;
import com.ninth_group.utils.QueryUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Repository;

import java.util.List;


@Repository
public class CityDaoImpl implements CityDao {
    @Resource
    private QueryUtil queryUtil;

    private static final String TABLE_NAME = "city_base_info";

    /**
     * 根据城市和省份名称获取城市信息
     * @param cityIds 城市id集合
     * @return 城市基本信息
     */
    @Override
    public City getCityBaseInfo(List<String> cityIds) {
        return getCityBaseInfo(
                TABLE_NAME,
                cityIds,
                City.class,
                QueryUtil::getCityById);
    }

    /**
     * 根据城市和省份名称获取城市信息
     * @param tableName 表名
     * @param cityIds 城市id集合
     * @param clazz  返回的类
     * @param getCityIdFunc 获取城市代码的函数
     * @return 城市基本信息
     */
    public <T> T getCityBaseInfo(String tableName,
                                 List<String> cityIds,
                                 Class<T> clazz,
                                 TriFunction<String, String, Class<T>, T> getCityIdFunc
    ) {
        Object cityData = queryUtil.getCityData(
                tableName,
                cityIds,
                clazz,
                getCityIdFunc,
                null);
        if (cityData == null) {
            return null;
        }

        if (!clazz.isInstance(cityData)) {
            throw new ClassCastException("Expected type: " + clazz.getName() +
                    ", but got: " + cityData.getClass().getName());
        }

        return clazz.cast(cityData);
    }

}
